package com.example.restatr.Atcivity.Main;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.example.restatr.Atcivity.Main.Fragment.UserFragment;
import com.example.restatr.R;
import com.example.restatr.Tools;
import com.google.android.material.button.MaterialButton;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class UserCenterAt extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
    private Toolbar tb;
    private TextView barTitle;
    private EditText search;
    private ImageView infoHead;
    private EditText infoNick;
    private EditText infoPhone;
    private EditText infoEmail;
    private EditText infoSfz;
    private RadioButton infoNan;
    private RadioButton infoNv;
    private Uri uriForFile;
    private File file = null;
    private String fileName;
    private PopupWindow popupWindow;
    private MaterialButton GrzxCommit;
    private RelativeLayout zzc;
    private LinearLayout jdt;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_grzx_at);

        tb = findViewById(R.id.toolbar);
        barTitle = findViewById(R.id.bar_Title);
        search = findViewById(R.id.search);
        infoHead = findViewById(R.id.info_head);
        infoNick = findViewById(R.id.info_nick);
        infoPhone = findViewById(R.id.info_phone);
        infoEmail = findViewById(R.id.info_email);
        infoSfz = findViewById(R.id.info_sfz);
        infoNan = findViewById(R.id.info_nan);
        infoNv = findViewById(R.id.info_nv);
        GrzxCommit = findViewById(R.id.Grzx_Commit);
        zzc = findViewById(R.id.zzc);
        jdt = findViewById(R.id.jdt);

        Tools.SetBarTitle( tb,barTitle,"个人资料",search, UserCenterAt.this,false );
        //获取用户信息
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String get = Tools.Get("/prod-api/api/common/user/getInfo", UserFragment.token);
                if (get != null) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(get);
                                int code = jsonObject.getInt("code");
                                if (code == 200) {
                                    JSONObject user = jsonObject.getJSONObject("user");
                                    infoNick.setText(user.getString("nickName"));
                                    infoPhone.setText(user.getString("phonenumber"));
                                    infoEmail.setText(user.getString("email"));
                                    infoSfz.setText(user.getString("idCard"));
                                    String sex = user.getString("sex");
                                    if (sex.equals("0")) {
                                        infoNan.setChecked(true);
                                        infoNv.setChecked(false);
                                    } else if (sex.equals("1")) {
                                        infoNv.setChecked(false);
                                        infoNv.setChecked(true);
                                    }
                                    Log.d( "TAG", "run: "+user.getString( "avatar" ) );
                                    Glide.with(UserCenterAt.this)
                                            .load(Tools.ip+user.getString("avatar"))
                                            .transform(new CircleCrop())
                                            .placeholder(R.drawable.ic_baseline_account_circle_24)
                                            .into(infoHead);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            }
        }).start();

    }

    /**
     * 修改用户信息并上传至服务器
     *
     * @param InfoEmail 邮箱
     * @param InfoSfz   身份证
     * @param InfoNick  昵称
     * @param InfoPhone 手机号
     * @param finalSex  性别
     * @param fileName  头像文件路径
     */
    private void SetUserInfo(final String InfoEmail, final String InfoSfz, final String InfoNick, final String InfoPhone, final String finalSex, final String fileName) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("email", InfoEmail);
                    jsonObject.put("idCard", InfoSfz);
                    jsonObject.put("nickName", InfoNick);
                    jsonObject.put("phonenumber", InfoPhone);
                    jsonObject.put("sex", finalSex);
                    if (fileName != null) {
                        jsonObject.put("avatar","/prod-api"+fileName);
                    }
                    final String put = Tools.Put("/prod-api/api/common/user", UserFragment.token, jsonObject.toString());
                    if (put != null) {
                        JSONObject jieXi = new JSONObject(put);
                        Looper.prepare();
                        Toast.makeText(UserCenterAt.this, jieXi.getString("msg"), Toast.LENGTH_SHORT).show();
                        Looper.loop();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    //Activity回调函数
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == DEFAULT_KEYS_DIALER) {
            if (resultCode == RESULT_OK) {
                try {
                    InputStream inputStream = getContentResolver().openInputStream(uriForFile);
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    Glide.with(UserCenterAt.this)
                            .load(bitmap)
                            .transform(new CircleCrop())
                            .into(infoHead);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
            Toast.makeText( UserCenterAt.this,"照片保存在："+file.getPath(),Toast.LENGTH_SHORT).show();
            //上传文件到服务器
            UploadImage(file);
        } else if (requestCode == DEFAULT_KEYS_DISABLE) {
            if (resultCode == RESULT_OK) {
                handleImageOnApi19(data);
            }
        }
    }

    //获取头像路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
        if (cursor != null) {
            if (cursor.moveToFirst()) {
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path;
    }

    private void resolveMSFContent(Uri uri, String documentId) {

        File file = new File(getCacheDir(), "temp_file" + getContentResolver().getType(uri).split("/")[1]);

        try {
            InputStream inputStream = getContentResolver().openInputStream(uri);

            OutputStream outputStream = new FileOutputStream(file);

            byte[] buffer = new byte[4 * 1024];
            int read;
            while ((read = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, read);
            }
            outputStream.flush();
            displayImage(file.getAbsolutePath());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //选择头像Api 19以上
    @TargetApi(19)
    private void handleImageOnApi19(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)) {
            String documentId = DocumentsContract.getDocumentId(uri);
            if (TextUtils.equals(uri.getAuthority(), "com.android.providers.media.documents")) {
                String id = documentId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if (TextUtils.equals(uri.getAuthority(), "com.android.providers.downloads.documents")) {
                if (documentId != null && documentId.startsWith("msf:")) {
                    resolveMSFContent(uri, documentId);
                    return;
                }
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                imagePath = getImagePath(contentUri, null);
            } else {
                String id = documentId.split(":")[1];
                imagePath = "/storage/emulated/0/" + id;
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            imagePath = getImagePath(uri, null);
        } else if ("file".equalsIgnoreCase(uri.getScheme())) {
            imagePath = uri.getPath();
        }
        displayImage(imagePath);
    }

    /**
     * 上传图片到服务器
     */
    private void UploadImage(final File mfile) {
        zzc.setVisibility(View.VISIBLE);
        jdt.setVisibility(View.VISIBLE);
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String s = Tools.UploadFiles("/prod-api/common/upload", UserFragment.token, mfile);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        if (s != null) {
                            try {
                                JSONObject JieXi = new JSONObject(s);
                                if (JieXi.getInt("code") == 200) {
                                    fileName = JieXi.getString("fileName");
                                    zzc.setVisibility(View.GONE);
                                    jdt.setVisibility(View.GONE);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
            }
        }).start();
    }

    //popupWindow按钮点击事件
    public void ppWindowClick(View view) {
        switch (view.getId()) {
            case R.id.pz:
                file = new File(getExternalCacheDir(), System.currentTimeMillis() + ".jpg");
                if (!file.exists()) {
                    try {
                        file.createNewFile();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                uriForFile = FileProvider.getUriForFile(UserCenterAt.this, "com.example.restatr.fileprovider", file);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uriForFile);
                startActivityForResult(intent, UserCenterAt.DEFAULT_KEYS_DIALER);
                popupWindow.dismiss();
                break;
            case R.id.xc:
                choosePhoto();
                popupWindow.dismiss();
                break;
            case R.id.qx:
                popupWindow.dismiss();
                break;
        }
    }

    //显示头像
    private void displayImage(String imagePath) {
        if (imagePath != null) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            Glide.with(UserCenterAt.this)
                    .load(bitmap)
                    .placeholder(R.drawable.ic_baseline_account_circle_24)
                    .transform(new CircleCrop())
                    .into(infoHead);
            File file = new File(imagePath);
            UploadImage(file);
        }
    }

    //检测相册权限
    public void choosePhoto() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
            // 真正的去打开相册
            openAlbum();
        } else {
            // 去申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
        }
    }

    //权限申请回调
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        //当接受申请时，打开相册
        if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
            openAlbum();
        }
    }

    //打开相册
    private void openAlbum() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, DEFAULT_KEYS_DISABLE);
    }

    //上传头像和提交修改点击事件
    public void GrzxClick(View view) {
        switch (view.getId()) {
            case R.id.sctx:
                View inflate = getLayoutInflater().inflate(R.layout.popupwindow_layout, null);
                popupWindow = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setAnimationStyle(R.style.anim_photo_select);
                popupWindow.showAtLocation(GrzxCommit, Gravity.BOTTOM, 0, 0);
                popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                        zzc.setVisibility(View.GONE);
                    }
                });
                zzc.setVisibility(View.VISIBLE);
                break;
            case R.id.Grzx_Commit:
                final String InfoNick = infoNick.getText().toString();
                final String InfoEmail = infoEmail.getText().toString();
                final String InfoPhone = infoPhone.getText().toString();
                final String InfoSfz = infoSfz.getText().toString();
                String sex = null;
                if (infoNan.isChecked()) {
                    sex = "0";
                } else {
                    sex = "1";
                }
                final String finalSex = sex;
                //修改用户信息
                SetUserInfo(InfoEmail, InfoSfz, InfoNick, InfoPhone, finalSex, fileName);
                break;
        }
    }

}